package com.googlecode.montelin.server;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.QueryResultIterable;
import com.google.appengine.repackaged.com.google.common.base.Joiner;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.googlecode.montelin.server.dao.DAO;
import com.googlecode.montelin.server.domain.Configuration;
import com.googlecode.montelin.server.domain.Page;
import com.googlecode.montelin.server.domain.User;

@SuppressWarnings("serial")
public class AbstractMontelinServlet extends HttpServlet {

	Random rand = new Random();

	public AbstractMontelinServlet() {
		super();
		Injector injector = Guice.createInjector(new Module());
		dao = injector.getInstance(DAO.class);
	}

	protected DAO dao;

	private static final String STARTCONTENT = "<tr><td id=\"content\"><table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" width=\"100%\"><tr>";

	private static final String MENU = "<td class=\"menu\">"
			+ "<table width=\"100%%\"  border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"bloc\">"
			+ "<tr>"
			+ "<td>%1$s<img src=\"images/pineaublanc.jpg\" width=\"150px\" alt=\"Pineau Blanc des Charentes\" style=\" \" /><br /></td>"
			+ "</tr>" + "</table>" + "</td>";

	private static final String CONTENT = "<td class=\"main\">%1$s</td>";

	private static final String ENDCONTENT = "</tr></table></td></tr>";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html");
		String code = req.getParameter(Constants.CODE_PARAMETER);
		String cat = req.getParameter(Constants.CAT_PARAMETER);
		if (code == null) {
			code = Constants.DEFAULT_CODE;
		}

		// TODO RCR
		String lang = null;
		if (lang == null) {
			lang = Constants.DEFAULT_LANGUAGE;
		}

		String skel;
		skel = generateSkeleton(code, cat, lang);
		resp.getWriter().print(skel);
	}

	private final String DOCTYPE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			+ Constants.SEPARATOR
			+ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
			+ Constants.SEPARATOR
			+ "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"%1$s\" xml:lang=\"%1$s\">";

	private final String HEAD = "<head>"
			+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-1\" />"
			+ "<meta http-equiv=\"content-language\" content=\"%1$s\" />"
			+ "<meta name=\"robots\" content=\"%2$s\" />"
			+ "<meta name=\"keywords\" content=\"%3$s\" />"
			+ "<meta name=\"description\" content=\"%4$s\" />"
			+ "<meta name=\"rating\" content=\"%5$s\" />"
			+ "<meta name=\"author\" content=\"%6$s\" />"
			+ "<meta name=\"copyright\" content=\"%7$s\" />"
			+ "<title>"
			+ "%8$s"
			+ "</title>"
			+ "<link href=\"favicon.ico\" rel=\"shortcut icon\" />"
			+ "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"style.css\" />"
			+ "</head>";

	private final String BODY = "<body>"
			+ "<table id=\"page\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">";
	private final String ENDBODY = "</table>"
			+ "<br />"
			+ "<div style=\"text-align:center\">"
			+ "	<img src=\"images/logo_PDC2.gif\" alt=\"logo du pineau des charentes\" /><br/>"
			+ "	<img src=\"images/mouettes.gif\" alt=\"Le charente-maritime: de terre et d'océan\" />"
			+ "</div>" + "</body>" + "</html>";

	private final String BANDEAU = "<tr>"
			+ "<td id=\"head\">"
			+ "	<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" width=\"100%%\">"
			+ "		<tr>"
			+ "			<td class=\"bandeau\">"
			+ "				<span class=\"bandeau\">%1$s</span>"
			+ "			</td>"
			+ "		</tr>"
			+ "		<tr>"
			+ "			<td id=\"logo\">"
			+ "				<a href=\"/\"><img src=\"images/logo.jpg\" alt=\"Montelin\" border=\"0\" /></a>"
			+ "			</td>" + "		</tr>" + "	</table>" + "</td>" + "</tr>";

	private final String FOOTER = "<tr>"
			+ "<td id=\"foot\">"
			+ "	<table cellspacing=\"0\" cellpadding=\"0\" align=\"center\" width=\"100%%\">"
			+ "		<tr>"
			+ "			<td class=\"bandeau\">"
			+ "				<span class=\"bandeau\">Informations pratiques</span>"
			+ "			</td>"
			+ "		</tr>"
			+ "		<tr>"
			+ "			<td id=\"info_foot\">"
			+ "				<table width=\"97%%\"  border=\"0\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">"
			+ "				  <tr>"
			+ "					<td colspan=\"2\" align=\"center\"><p>%3$s<br />"
			+ "						%6$s<br />"
			+ "						%7$s %5$s</p></td>"
			+ "				  </tr>"
			+ "				  <tr>"
			+ "					<td align=\"left\"><u>Tel/fax:</u> %4$s</td>"
			+ "					<td align=\"right\"><u>Mail:</u> <a href=\"mailto:%1$s\">%1$s</a></td>"
			+ "				  </tr>" + "				</table>" + "			</td>" + "		</tr>"
			+ "	</table>" + "</td>" + "</tr>";

	private String generateSkeleton(String code, String cat, String lang) {
		StringBuilder b = new StringBuilder();
		User earl = dao.findUserByName(Constants.DEFAULT_USER);
		Configuration conf = dao.findConfigurationByLang(lang);
		Page page;
		if (cat != null)
			page = dao.findPageByCodeAndLang(cat, lang);
		else {
			page = dao.findPageByCodeAndLang(code, lang);
		}

		b.append(String.format(DOCTYPE, lang));
		b.append(Constants.SEPARATOR);
		Joiner join = Joiner.on(",").skipNulls();

		b.append(String.format(HEAD, page.getLang(), conf.getRobots(),
				join.join(conf.getKeywords(), page.getKeywords()),
				page.getDescription(), conf.getRating(), conf.getAuthor(),
				conf.getCopyright(), page.getTitle()));
		b.append(Constants.SEPARATOR);
		b.append(BODY);
		b.append(Constants.SEPARATOR);

		b.append(String.format(BANDEAU, conf.getSlogan()));
		b.append(Constants.SEPARATOR);
		b.append(STARTCONTENT);
		b.append(Constants.SEPARATOR);

		b.append(Constants.SEPARATOR);
		String menu = generateMenu(code, cat, lang);
		b.append(String.format(MENU, menu));
		b.append(Constants.SEPARATOR);
		b.append(String.format(CONTENT,
				String.format(page.getContent(), "0" + (rand.nextInt(9) + 1))));
		b.append(Constants.SEPARATOR);

		b.append(Constants.SEPARATOR);
		b.append(ENDCONTENT);
		b.append(Constants.SEPARATOR);
		b.append(String.format(FOOTER, earl.getMail(), earl.getFax(), earl
				.getName(), earl.getPhone(), earl.getAddress().getCity(), earl
				.getAddress().getStreet(), earl.getAddress().getPostalCode()));
		b.append(Constants.SEPARATOR);

		b.append(Constants.SEPARATOR);
		b.append(ENDBODY);
		return b.toString();
	}

	private static final String MENU_LEVEL_1 = "<span class=\"%1$s\"><a href=\"?page=%2$s\">%3$s</a></span>";

	private String generateMenu(String code, String cat, String lang) {
		QueryResultIterable<Page> pages = dao.findAllRootPages(lang);
		StringBuilder output = new StringBuilder();
		for (Page page : pages) {
			output.append(String.format(MENU_LEVEL_1, "up "
					+ (page.getCode().equals(code) ? "actif_up"
							: ""), page.getCode(), page.getMenuCaption()));
			for (Page subpage : page.getChildren()) {
				output.append(String.format(
						MENU_LEVEL_1,
						"down "
								+ (subpage.getCode().equals(
										cat) ? "actif_down"
										: ""),
						page.getCode() + "&" + Constants.CAT_PARAMETER + "="
								+ subpage.getCode(), subpage.getMenuCaption()));

			}
		}
		return output.toString();
	}
}
